package com.athenaeum.dataxplore.controller;

import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.athenaeum.datastore.criteria.MailCriteria;
import com.athenaeum.datastore.domain.Mail;
import com.athenaeum.datastore.domain.Project;
import com.athenaeum.datastore.domain.User;
import com.athenaeum.datastore.domain.UserGroup;
import com.athenaeum.datastore.enums.MailType;
import com.athenaeum.datastore.enums.RecipientType;
import com.athenaeum.datastore.service.MailService;
import com.athenaeum.datastore.service.UserService;
import com.athenaeum.datastore.util.UserUtil;

@Controller
public class MailController {
	private static final Logger log = LoggerFactory.getLogger(MailController.class);
	
	@Autowired
	private MailService mailService;
	@Autowired
	private UserService userService;
	
	private int pageSize = 10;
	private int pageNumber = 1;
	/*
	 * Type is INBOX, SENT, DRAFTS and DELETED etc
	 */
	@RequestMapping(value = "user/mail/list/{mailtype}/{page}/{size}", method = RequestMethod.GET)
	public @ResponseBody Page<Mail> list(Locale locale, Model model,
			@PathVariable("mailtype") String mailType,
			@PathVariable("page") int page,
			@PathVariable("size") int size) {
		String username = UserUtil.getUsernameInContext();
		log.info("Loading Settings - Mail("+mailType+")'s for User:"+username);
		User loggedInUser = userService.findOne(username);
		String emailId = loggedInUser.getId();
		MailCriteria mailCriteria = new MailCriteria();
		mailCriteria.setEmail(emailId);
		MailType type = MailType.getMailType(mailType);
		mailCriteria.setMailType(type);
		switch(type) {
		case INBOX:
			mailCriteria.setRecipientTypes(RecipientType.TO, RecipientType.CC, RecipientType.BCC);
			break;
		case SENT:
			mailCriteria.setRecipientTypes(RecipientType.FROM);
			break;
		}
		if(page > 0) {
			pageNumber = page;
		}
		if(size > 0) {
			pageSize = size;
		}
		Pageable pageable = new PageRequest(pageNumber, pageSize);
		Page<Mail> mailPage = mailService.getByCriteria(mailCriteria, pageable);
		return mailPage;
	}
}
